﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using eStore.Models;
using eStore.ViewModels;

namespace eStore.Controllers
{
    public class CartController : Controller
    {
        private IProductRepository _productRepo = null;

        public CartController():this(new ProductRepository())
        {

        }

        public CartController(IProductRepository productRepo) {
            _productRepo = productRepo;
        }

        //
        // GET: /Cart/

        public ActionResult Index()
        {
            var shoppingCart = ShoppingCart.GetCart(this.HttpContext, false);
            var oViewModel = new CartIndexViewModel();
            if (shoppingCart != null)
            {
                var allCartItems = shoppingCart.GetAllCartItems();
                oViewModel.PageTitle = "My Carts";
                oViewModel.CartItems = allCartItems;
            }
            return View(oViewModel);
        }

        [ChildActionOnly]
        public ActionResult CartCounterMenu() {
            var shoppingCart = ShoppingCart.GetCart(this.HttpContext, false);
            int iCounter = 0;
            if (shoppingCart != null)
                iCounter= shoppingCart.TotalCartItemsCount();
            dynamic cartCounterViewModel = new System.Dynamic.ExpandoObject();
            cartCounterViewModel.CartCounter = iCounter.ToString();
            return View(cartCounterViewModel);
        }

        [ChildActionOnly]
        public ActionResult MiniCartWidget() {
            var shoppingCart = ShoppingCart.GetCart(this.HttpContext, false);
            List<CartItem> allCartItems = null;
            if (shoppingCart != null)
            {
                allCartItems = shoppingCart.GetAllCartItems();
            }
            return PartialView(allCartItems);
        }

        public ActionResult AddToCart(FormCollection collections) {
            var productId = collections.GetValue("productid").AttemptedValue;
            var matchedProduct = _productRepo.GetById(productId);
            var shoppingCart = ShoppingCart.GetCart(this.HttpContext, false);
            if (matchedProduct != null)
                shoppingCart.AddItem(matchedProduct);

            return RedirectToAction("Index");
        }

        public ActionResult AddToWishList(FormCollection collection) {
            
            return View();
        }

    }   
}
